import { MenuProps } from "antd";
import {
  HomeOutlined,
  UserOutlined,
  DashboardOutlined,
  SettingOutlined,
  AppstoreOutlined,
  HddOutlined,
  ForkOutlined,
  ApartmentOutlined,
  SnippetsOutlined,
  FieldTimeOutlined,
  ContainerOutlined,
  ProfileOutlined,
  NotificationOutlined,
  ControlOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  MonitorOutlined,
  BarChartOutlined,
  SecurityScanOutlined,
  FireOutlined,
  MenuOutlined,
} from "@ant-design/icons";
import { useState, useEffect } from "react";
import { system } from "@/forent-api/api";

// 图标映射
const IconMap: Record<string, any> = {
  HomeOutlined,
  UserOutlined,
  DashboardOutlined,
  SettingOutlined,
  AppstoreOutlined,
  HddOutlined,
  ForkOutlined,
  ApartmentOutlined,
  SnippetsOutlined,
  FieldTimeOutlined,
  ContainerOutlined,
  ProfileOutlined,
  NotificationOutlined,
  ControlOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  MonitorOutlined,
  BarChartOutlined,
  SecurityScanOutlined,
  FireOutlined,
  MenuOutlined,
};

// 获取图标组件
export const getIconComponent = (iconName: string) => {
  if (!iconName) return <MenuOutlined />;
  const Icon = IconMap[iconName];
  return Icon ? <Icon /> : <MenuOutlined />;
};

// 静态菜单 - 超级管理员专用
const getSuperAdminMenuItems = (): MenuProps["items"] => {
  return [
    {
      key: `/agent/system/home`,
      icon: <HomeOutlined />,
      label: "系统首页",
    },
    {
      key: `/agent/system/dept`,
      icon: <ApartmentOutlined />,
      label: "机构管理",
    },
    {
      key: `/agent/system/dict`,
      icon: <ContainerOutlined />,
      label: "字典管理",
    },
    {
      key: `/agent/system/rbac`,
      icon: <UserOutlined />,
      label: "角色管理",
    },
    {
      key: `/agent/system/menu`,
      icon: <MenuOutlined />,
      label: "菜单管理",
    },
    {
      key: `/agent/system/timer`,
      icon: <FieldTimeOutlined />,
      label: "定时管理",
    },
    {
      key: `/agent/system/log`,
      icon: <ProfileOutlined />,
      label: "日志管理",
    },
    {
      key: `/agent/system/setting`,
      icon: <SettingOutlined />,
      label: "系统配置",
    },
    {
      key: `/agent/system/notice`,
      icon: <NotificationOutlined />,
      label: "消息通知",
    },
  ];
};

// 将后端菜单数据转换为Antd菜单项格式
export const convertToMenuItems = (menuData: any[]): MenuProps["items"] => {
  return menuData.map((item) => {
    const menuItem: any = {
      key: item.menu_path,
      icon: getIconComponent(item.icon),
      label: item.menu_name,
    };

    // 如果有子菜单，递归处理
    if (item.children && item.children.length > 0) {
      menuItem.children = convertToMenuItems(item.children);
    }

    return menuItem;
  });
};

// 主函数 - 获取导航菜单项
export async function getNavigationItems(
  user_type: string,
  userInfoResult: any
): Promise<MenuProps["items"]> {
  const defaultMenu = [
    {
      key: user_type === "01" ? `/agent/main/home` : "/agent/system/home",
      icon: <HomeOutlined />,
      label: "首页",
    },
  ];

  // 超级管理员使用静态菜单
  if (user_type === "00") {
    return getSuperAdminMenuItems();
  }

  // 其他用户尝试从后端获取动态菜单
  try {
    // 首先尝试从本地缓存获取菜单
    const cachedMenus = localStorage.getItem("user_menus");

    // 如果有缓存并且不是太旧，直接使用缓存
    if (cachedMenus) {
      const { data, timestamp } = JSON.parse(cachedMenus);
      // 缓存10分钟内有效
      if (Date.now() - timestamp < 10 * 60 * 1000 && data) {
        const menuItems = convertToMenuItems(data);
        return [...defaultMenu, ...(menuItems || [])];
      }
    }

    // 缓存过期或不存在，从API获取
    const response = await system.getUserMenu({
      userType: user_type,
      roleType: userInfoResult.role_type || "",
    });
    if (response?.data) {
      // 缓存结果
      localStorage.setItem(
        "user_menus",
        JSON.stringify({
          data: response.data,
          timestamp: Date.now(),
        })
      );

      const menuItems = convertToMenuItems(response.data);
      return [...defaultMenu, ...(menuItems || [])];
    }

    // 默认至少显示首页
    return defaultMenu;
  } catch (error) {
    // 异常情况下，显示首页
    return defaultMenu;
  }
}
